import {
    APIS
} from "./API"

const apis = APIS
const app = getApp()
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : `0${n}`
}



function login() {
    return new Promise(function (resolve, reject) {
        wx.login({
            success(res) {
                if (res.code) {
                    console.log("发送登录信息")
                    wx.showLoading({
                        title: '正在登录',
                        mask: true
                    })
                    //发起网络请求
                    wx.request({
                        url: app.globalData.domainName + apis.login.url,
                        data: {
                            code: res.code,
                        },
                        method: apis.login.method,
                        success(ress) {
                            wx.hideLoading()
                            if (app.globalData.intest) {
                                console.log(ress);
                            }
                            app.globalData.header['Cookie'] = ress.header['Set-Cookie'].split(';')[0];
                            app.globalData.userInfo["username"] = ress.data.username;
                            console.log("登陆成功");
                            app.globalData.hasLogin = true
                            resolve(ress.data)
                        },
                        fail(ress) {
                            wx.hideLoading()
                            wx.showToast({
                                title: '网络故障',
                                icon: "error",
                                mask: true
                            })
                            reject(ress)
                        }
                    })
                } else {
                    wx.showToast({
                        title: '登陆失败',
                        mask: true
                    })
                    setTimeout(function () {
                        wx.hideToast()
                    }, 2000)
                }
            }
        })
    })

}

function request({
    url,
    data,
    method
}) {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: app.globalData.domainName + url,
            data: data,
            method: method,
            success(ress) {
                //请求成功
                //判断状态码---errCode状态根据后端定义来判断
                if (app.globalData.intest) {
                    console.log(ress)
                }
                if (ress.statusCode != 200) {
                    wx.showToast({
                        title: '后端炸啦',
                        icon: "error"
                    })
                    return
                }
                if (ress.data.ret == 2) {
                    app.globalData.hasLogin = false;
                    wx.switchTab({
                        url: '/pages/userInf/userInf',
                    }).then(function (e) {
                        wx.showToast({
                            title: '请先登录',
                            icon: "error"
                        })
                    })
                } else {
                    resolve(ress);
                }
            },
            fail(err) {
                //请求失败
                wx.showToast({
                    title: '网络故障',
                    icon: "error"
                })
                reject(err)
            },
            header: app.globalData.header
        })
    })
}

function resetPageDataInGlobal() {
    app.globalData.problemLunchData = null
    app.globalData.answerHistory = null
}

function navBack() {
    wx.navigateBack({
        delta: 1,
    })
}

function setNavData(page) {
    let app = getApp()
    if (!setNavData.flag) {
        wx.getSystemInfo({
            success: e => {
                app.globalData.navBarData.StatusBar = e.statusBarHeight;
                let px2rpx = 750 / e.screenWidth
                let tabbarHeight = e.screenHeight - e.windowHeight
                let screenHeight = e.screenHeight
                app.globalData.navBarData.screenHeight = screenHeight
                app.globalData.navBarData.windowHeight = e.windowHeight
                app.globalData.navBarData.tabbarHeight = tabbarHeight
                app.globalData.navBarData.searchbarHeight = 100 / px2rpx
                let capsule = wx.getMenuButtonBoundingClientRect();
                if (capsule) {
                    app.globalData.navBarData.Custom = capsule;
                    app.globalData.navBarData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
                } else {
                    app.globalData.navBarData.CustomBar = e.statusBarHeight + 50;
                }
                app.globalData.navBarData.safeHeight = e.screenHeight - app.globalData.navBarData.CustomBar
            }
        })
    }
    page.setData({
        navBarData: app.globalData.navBarData
    })
    setNavData.flag = true
}
setNavData.flag = false

function vibrateShort() {
    wx.vibrateShort({
        type: 'heavy',
    }).catch(function () {})
}

const ColorList = [{
        title: '嫣红',
        name: 'red',
        color: '#e54d42'
    },
    {
        title: '桔橙',
        name: 'orange',
        color: '#f37b1d'
    },
    {
        title: '明黄',
        name: 'yellow',
        color: '#fbbd08'
    },
    {
        title: '橄榄',
        name: 'olive',
        color: '#8dc63f'
    },
    {
        title: '森绿',
        name: 'green',
        color: '#39b54a'
    },
    {
        title: '天青',
        name: 'cyan',
        color: '#1cbbb4'
    },
    {
        title: '海蓝',
        name: 'blue',
        color: '#0081ff'
    },
    {
        title: '姹紫',
        name: 'purple',
        color: '#6739b6'
    },
    {
        title: '木槿',
        name: 'mauve',
        color: '#9c26b0'
    },
    {
        title: '桃粉',
        name: 'pink',
        color: '#e03997'
    },
    {
        title: '棕褐',
        name: 'brown',
        color: '#a5673f'
    },
    {
        title: '玄灰',
        name: 'grey',
        color: '#8799a3'
    },
    {
        title: '草灰',
        name: 'gray',
        color: '#aaaaaa'
    },
    {
        title: '墨黑',
        name: 'black',
        color: '#333333'
    },
    {
        title: '雅白',
        name: 'white',
        color: '#ffffff'
    },
]

function getRandomColor(withoutGrayWhiteBlack) {
    let arr = ColorList
    do {
        let index = Math.floor(Math.random() * arr.length)
        if (!withoutGrayWhiteBlack) {
            return ColorList[index]
        }
        if (ColorList[index].name != 'gray' && ColorList[index].name != 'white' && ColorList[index].name != 'black') {
            return ColorList[index]
        }
    } while (true)
}


module.exports = {
    formatTime: formatTime,
    login: login,
    request: request,
    APIS: apis,
    resetGlobalData: resetPageDataInGlobal,
    navBack: navBack,
    initGlobalData: setNavData,
    vibrateShort: vibrateShort,
    ColorList: ColorList,
    getRandomColor: getRandomColor
}